<template>
  <div ref="chart" class="chart"></div>
</template>
<script setup>
import { ref, reactive, watch } from 'vue'
import { taskMap } from '../data'
import { useEcharts } from '@/hooks'
import { getColorByRate } from '@/views/target-boost/utils'
const props = defineProps({
  practiceRecordArray: Array,
  goToTask: Function,
  isLoading: Boolean
})
const isShowTaskDetail = taskFrom => {
  return taskFrom !== '自'
}
const chart = ref(null)
let option = reactive({
  tooltip: {
    trigger: 'item',
    formatter: function (params) {
      return `<div>
         <p>任务名称：${params.data[3].task_name}</p>
         <p>练习时间: ${params.data[2]}</p>
         <p>正确率: <span style="color:${getColorByRate(params.data[1] / 100)}">${params.data[1]}%</span></p>
         <p>习题量: ${params.data[3].count}</p>
      ${isShowTaskDetail(taskMap[params.data[3].task_from]) ? '<span style="color:#ccc">点击查看任务详情</span>' : ''}
       </div>`
    },
    borderColor: '#fff',
    appendToBody: true
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    // 隐藏
    show: false
  },
  yAxis: {
    type: 'value',
    axisLabel: {
      color: '#9B9B9B'
    },
    min: 0,
    max: 100,
    splitNumber: 5
  },
  grid: {
    top: '10px',
    left: '25px',
    right: '10px',
    bottom: '25px'
  },
  series: [
    {
      name: '满分',
      type: 'line',
      itemStyle: {
        color: function (params) {
          return params.value[1] === 100 ? '#F1A42F' : '#F60000'
        }
      },
      lineStyle: {
        color: '#428FFF'
      }
    }
  ]
})
// 使用chartInstance要要.value
const { chartInstance, showLoading, hideLoading, addEvent } = useEcharts(
  chart,
  option
)
console.log(chartInstance.value)

addEvent('click', params => {
  props.goToTask(params.data[3])
})

watch(
  () => [props.practiceRecordArray, props.isLoading],
  async () => {
    if (props.isLoading) {
      await showLoading()
    }
    option.series[0].data = props.practiceRecordArray
    if (!props.isLoading) {
      await hideLoading()
    }
    console.log(option.series[0].data)
  },
  {
    immediate: true
  }
)
</script>
<style lang="less" scoped>
.chart {
  width: 100%;
  height: 150px;
}
</style>
